package controller

import (
	"html/template"
	"net/http"
	"strconv"

	"gitee.com/shuwenhe/shuwen-mall/model"

	"gitee.com/shuwenhe/shuwen-mall/dao"
)

func GetItems(w http.ResponseWriter, r *http.Request) {
	items, _ := dao.GetItems()
	t := template.Must(template.ParseFiles("views/pages/manager/book_manager.html"))
	t.Execute(w, items)
}

// AddItems 添加商品
func AddItems(w http.ResponseWriter, r *http.Request) {
	title := r.FormValue("title")
	price := r.FormValue("price")
	author := r.FormValue("author")
	sales := r.FormValue("sales")
	stock := r.FormValue("stock")

	priceFloat, _ := strconv.ParseFloat(price, 64)
	salesInt, _ := strconv.Atoi(sales)
	stockInt, _ := strconv.Atoi(stock)

	item := &model.Item{
		Title:   title,
		Author:  author,
		Price:   priceFloat,
		Sales:   salesInt,
		Stock:   stockInt,
		ImgPath: "/static/img/default.jpg",
	}
	dao.AddItems(item)
	GetItems(w, r)
}

func DeleteItem(w http.ResponseWriter, r *http.Request) {
	ID := r.FormValue("bookId") // <td><a href="/deleteItem?bookId={{.ID}}">删除</a></td>
	dao.DeleteItem(ID)
	GetItems(w, r)
}

func GetItemByID(w http.ResponseWriter, r *http.Request) {
	ID := r.FormValue("bookId")
	item, _ := dao.GetItemByID(ID)
	t := template.Must(template.ParseFiles("views/pages/manager/book_modify.html"))
	t.Execute(w, item)
	// GetItems(w, r)
}

func UpdateItem(w http.ResponseWriter, r *http.Request) {
	r.FormValue("bookId")
	item := &model.Item{}
	dao.UpdateItem(item)
}
